# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html

import pymongo
import logging
logger = logging.getLogger(__name__)

class DutyfreePipeline(object):
    def process_item(self, item, spider):
        return item

class MongoPipeline(object):
    collection_item = 'items'
   
    def __init__(self, mongo_uri, mongo_db):
        self.mongo_uri = mongo_uri
        self.mongo_db = mongo_db

    @classmethod
    def from_crawler(cls, crawler):
        return cls(
            mongo_uri=crawler.settings.get('MONGO_URI'),
            mongo_db=crawler.settings.get('MONGO_DATABASE')
        )

    def open_spider(self, spider):
        self.client = pymongo.MongoClient(self.mongo_uri)
        self.db = self.client[self.mongo_db]

    def close_spider(self, spider):
        self.client.close()
        
    def process_item(self, item, spider):
        if len(item)<2:
            return
        dict_item = item
        dict_item['_id'] = int(item['url'].split('/')[-1])
        #print dict_item
        try:
            self.db[self.collection_item].insert(dict_item)
        except pymongo.errors.DuplicateKeyError:
            logger.debug('_id %s has been existed', dict_item["_id"])